package com.fsnbigdata.web;

import com.fsnbigdata.domain.Kopp;
import com.fsnbigdata.domain.ZhKopp;
import com.fsnbigdata.enums.ResultEnum;
import com.fsnbigdata.exception.ParamException;
import com.fsnbigdata.service.api.ZhKoppService;
import com.fsnbigdata.util.ChineseInital;
import com.fsnbigdata.util.ReflectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.annotations.ControllerType;
import org.springframework.roo.addon.web.mvc.controller.annotations.RooController;
import org.springframework.roo.addon.web.mvc.controller.annotations.responses.json.RooJSON;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.lang.reflect.Method;
import java.security.Principal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by chen quan zhou on 2018/8/28.
 */
@RooController(entity = ZhKopp.class, pathPrefix = "/api", type = ControllerType.COLLECTION)
@RooJSON
@RestController
@RequestMapping(value = "/api/zhkopp",name = "ZhKoppController", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = "ZhKopp", description = "生物科普" )
public class ZhKoppController {

    @Autowired
    private ZhKoppService zhKoppService;

    /**
     * 根据id查询
     * @param request
     * @return
     */
    @GetMapping("findOne")
    public Kopp findById(HttpServletRequest request){
        Long id = Long.parseLong( request.getParameter( "id" ) );
        return zhKoppService.findById(id);
    }


    /**
     * 返回所有列表数据
     * @return
     */
    @GetMapping(value = "list")
    public List<ZhKopp> list(){
        return zhKoppService.findAll();
    }


    /**
     * 根据字母索引查询
     * @param request
     * @return
     */
    @GetMapping(value = "queryByAlphabet")
    public List<ZhKopp> queryByAlphabet(HttpServletRequest request){
        String initial = request.getParameter( "initial" );
        return zhKoppService.queryByAlphabet(initial==null||"".equals( initial )?"a":initial);
    }

    /**
     * 根据关键字进行搜索
     * @param
     * @param name
     * @param pageable
     * @return
     */
    @GetMapping(name = "search", value = "advanceSearch")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    @PreAuthorize("hasRole('DB_ZHKOPP')")
    public Page<ZhKopp> getList(@RequestParam(required = false)String name,
                                Authentication authentication,
                                Pageable pageable){
        List<String> authorities = authentication.getAuthorities().stream().map(it -> it.getAuthority()).collect(Collectors.toList());
        String creator=null;
        if(!authorities.contains("ROLE_USER_ADMIN")){
           creator = authentication.getName();
        }
        return zhKoppService.findByPageAndSize(name,creator,pageable);
    }
    
    /**
     * 新增
     * @param zhKopp
     * @param result
     * @return
     */
    @PostMapping(value = "save")
    @PreAuthorize("hasRole('DB_ZHKOPP')")
    @ApiOperation(value = "",notes = "save")
    public ResponseEntity<?> save(@Valid @RequestBody Kopp zhKopp, BindingResult result,Principal principal) throws Exception {
        if (zhKopp.getId()!=null){
            return ResponseEntity.status(HttpStatus.CONFLICT).build();
        }
        if (result.hasErrors()) {
            throw new ParamException(ResultEnum.PARAM_ERROR.getCode(),
                    result.getFieldError().getDefaultMessage());
        }

        if(zhKoppService.getData( zhKopp.getKingdom(),zhKopp.getPhylumn(),zhKopp.getT_class(),zhKopp.getT_order(),zhKopp.getZ_name() )!=null){
            return ResponseEntity.status(HttpStatus.CONFLICT).body("该科普名已存在！");
        }
        zhKopp.setInitial( ChineseInital.getFirstLetter( zhKopp.getZ_name().substring( 0,1 ) ) );
        zhKopp.setAdd_time(new Date());
        ZhKopp newZhkopp = zhKoppService.save(zhKopp,principal.getName());

        Class<?> clazz = ZhKoppController.class;
        Method method = clazz.getMethod("save", ReflectUtil.getPeremeterClass(clazz, "save"));
        ReflectUtil.setAnnotationOn(method,"新增生物科普，名称："+newZhkopp.getZ_name());

        return ResponseEntity.ok(newZhkopp);
    }

    /**
     * 获取分类表数据
     * @param request
     * @return
     */
    @GetMapping(value = "getTaxonomy")
    public Object getTaxonomy(HttpServletRequest request){
        String kingdom = request.getParameter( "kingdom" );
        String phylumn = request.getParameter( "phylumn" );
        String t_class = request.getParameter( "t_class" );
        String t_order = request.getParameter( "t_order" );

        return zhKoppService.getTaxonomy(kingdom,phylumn,t_class,t_order);
    }

    /**
     * 更新生物科普
     * @param zhKopp
     * @param result
     * @return
     */
    @PutMapping(value = "update")
    @PreAuthorize("hasRole('DB_ZHKOPP')")
    @ApiOperation(value = "",notes = "update")
    public ResponseEntity<?> update(@Valid @RequestBody Kopp zhKopp,BindingResult result,Principal principal) throws Exception {
        if (result.hasErrors()) {
            throw new ParamException(ResultEnum.PARAM_ERROR.getCode(),
                    result.getFieldError().getDefaultMessage());
        }
        Kopp kopp = zhKoppService.getData( zhKopp.getKingdom(),zhKopp.getPhylumn(),zhKopp.getT_class(),zhKopp.getT_order(),zhKopp.getZ_name() );
        if(kopp!=null&&!(zhKopp.getId().equals( kopp.getId()))){
            return ResponseEntity.status(HttpStatus.CONFLICT).body("该科普名已存在！");
        }
        String name = zhKoppService.findById(zhKopp.getId()).getZ_name();
        zhKopp.setAdd_time( new Date(  ) );
        zhKopp.setInitial( ChineseInital.getFirstLetter( zhKopp.getZ_name().substring( 0,1 ) ) );
        ZhKopp newZhkopp = zhKoppService.save(zhKopp,principal.getName());

        Class<?> clazz = ZhKoppController.class;
        Method method = clazz.getMethod("update", ReflectUtil.getPeremeterClass(clazz, "update"));
        ReflectUtil.setAnnotationOn(method,"更新生物科普，名称："+name);

        return ResponseEntity.ok(newZhkopp);
    }
    
    /**
     * 删除一条记录
     * @param zhKopp
     * @return
     */
    @DeleteMapping(name = "delete",value = "delete")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "", paramType = "path", dataType = "int", required = true)
    })
    @PreAuthorize("hasRole('DB_ZHKOPP')")
    @ApiOperation(value = "",notes = "delete")
    public ResponseEntity<?> delete(@ModelAttribute ZhKopp zhKopp) throws Exception {
        String name =  zhKoppService.findById(zhKopp.getId()).getZ_name();
        zhKoppService.deleteOne(zhKopp.getId());

        Class<?> clazz = ZhKoppController.class;
        Method method = clazz.getMethod("delete", ReflectUtil.getPeremeterClass(clazz, "delete"));
        ReflectUtil.setAnnotationOn(method,"删除生物科普，名称："+name);

        return ResponseEntity.ok().build();
    }

    /**
     * 删除多条记录
     * @param ids
     * @return
     */
    @DeleteMapping(name = "deleteMany", value = "deleteMany")
    @PreAuthorize("hasRole('DB_ZHKOPP')")
    public ResponseEntity<?> deleteMany(@PathVariable("ids") Collection<Long> ids){
        zhKoppService.delete(ids);
        return ResponseEntity.ok().build();
    }

    @GetMapping("getData")
    public Kopp getData(HttpServletRequest request){
        String kingdom = request.getParameter( "kingdom" );
        String phylumn = request.getParameter( "phylumn" );
        String t_class = request.getParameter( "t_class" );
        String t_order = request.getParameter( "t_order" );
        String z_name = request.getParameter( "z_name" );
        return zhKoppService.getData(kingdom,phylumn,t_class,t_order,z_name);
    }

    /**
     * 获取前台的树
     * @param request
     * @return
     */
    @GetMapping(value = "getTree")
    public List getTree(HttpServletRequest request){
        String kingdom = request.getParameter( "kingdom" );
        String phylumn = request.getParameter( "phylumn" );
        String t_class = request.getParameter( "t_class" );
        String t_order = request.getParameter( "t_order" );
        return zhKoppService.getTree(kingdom,phylumn,t_class,t_order);
    }


}
